<template>
  <div :class="className">
    <video ref="videoPlayer" class="video-js" muted></video>
    <div class="cover" v-if="isCover">
      <div class="btn btn-play" @click="play">
        <i class="fa fa-play-circle-o"></i>
      </div>
    </div>
    <!-- :style="{width:vWidth,height:vHeight}" -->
    <!-- 不要同时使用data-setup和选项对象 -->
  </div>
</template>

<script>
import videojs from 'video.js';
// 文档：
// https://videojs.com/guides/setup/#using-videojsgetplayer
// https://videojs.com/guides/vue/
import 'video.js/dist/video-js.css';

export default {
  name: 'VideoPlayer',
  props: {
    className: {
      type: Array,
      default: () => {
        return ['video-box', 'box-16b9'];
      },
    },
    options: {
      type: Object,
      default() {
        return {
          aspectRatio: '16:9',
          autoplay: false,
          muted: true,
          preload: 'auto',
          controls: true,
        };
      },
    },
    vData: {
      type: Object,
      default: () => {
        return {
          poster: '',
          urlVideo: '',
        };
      },
    },
  },
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      cover: true,
      player: null,
    };
  },
  methods: {
    test() {},
    initVideo(url) {
      this.vData.urlVideo = url;
      this.$nextTick(() => {
        let url = url || this.vData.urlVideo;
        let face = this.vData.poster;
        this.player = videojs(this.$refs.videoPlayer, this.options, () => {
          this.player.log('onPlayerReady', this);
          this.player.poster(face);
          this.player.src([{ src: url, type: 'application/x-mpegURL' }]);
        });
      });

      return;
    },
    play() {
      this.cover = false;
      this.player.play();
      this.player.muted(false);
      videojs.hook('error', (Player, Error) => {
        this.$emit('planB');
      });
    },
  },
  mounted: function () {
    console.log(this.vData.urlVideo);
    this.initVideo();
    this.play();
    bus.$on('获得推流地址', (res) => {
      this.$nextTick(() => {
        this.initVideo(res);
      });
    });
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose();
    }
    bus.$off('获得推流地址');
  },
};
</script>

<style scoped lang="less">
.video-box {
  width: 100%;
  height: 100%;
}
</style>